<?php
/*
 * 城市分站处理文件
 * 如果选择的是城市分站,则加载本文件来处理相关逻辑
 * @author     Mark <zhaody901@126.com>
 * @copyright  Copyright (c) 2013 lemon team
 * @version    $Id: fcb19e8ca386acf8649aa8fd88b8c5874ad9c7e8 $
 * @time       14-2-7 上午10:25
 */
defined('IN_IXDCW') or exit('Access Denied');
$AREA = PCache::read('area.php');
$c = array();
$city = Cookie::get('city');

if($city) {  // 已经选择了的城市
	list($cityid, $city_domain) = explode('|', $city);
	if( // 匹配主站
		strpos(SITE_URL, $_SERVER['HTTP_HOST']) === false &&
		// 匹配分站
		strpos($city_domain, $_SERVER['HTTP_HOST']) === false
	) {
		// 如果给定域名或者地址和网站实际不符,则重新配置cookie
		$c = $db->getOne("SELECT * FROM {$db->getPre()}city WHERE domain='http://".$_SERVER['HTTP_HOST']."/'");
		if($c) {
			Cookie::set('city', $c['areaid'].'|'.$c['domain'], $DT_TIME + 365*86400);
			$cityid = $c['areaid'];
		}
	}
} else {
	if(strpos(SITE_URL, $_SERVER['HTTP_HOST']) === false) {
		// 输入地址和网站url不符合, 检测是否存在此分站
		$c = $db->getOne("SELECT * FROM {$db->getPre()}city WHERE domain='http://".$_SERVER['HTTP_HOST']."/'");
		if($c) {
			Cookie::set('city', $c['areaid'].'|'.$c['domain'], $DT_TIME + 365*86400);
			$cityid = $c['areaid'];
		}
	} else {
		// 开启分站跳转, 不是管理员调用, 不是机器人
		if($DT['city_ip'] && !defined('DT_ADMIN') && !$DT_BOT) {
			// 是否开启了分站城市自动跳转, 查询ip库, 定义cityid
			$iparea = Area::ip2area($DT_IP);
			$result = $db->query("SELECT * FROM {$db->getPre()}city");
			while($r = $db->fetchArray($result)) {
				if(preg_match("/".$r['name'].($r['iparea'] ? '|'.$r['iparea'] : '')."/i", $iparea)) {
					Cookie::set('city', $r['areaid'].'|'.$r['domain'], $DT_TIME + 365*86400);
					$cityid = $r['areaid'];
					if($r['domain']) dheader($r['domain']);
					$c = $r;
					break;
				}
			}
		}
	}
}

// 处理分站ID
if($cityid) {
	$c or $c = $db->getOne("SELECT * FROM {$db->getPre()}city WHERE areaid=$cityid");
	if(!defined('DT_ADMIN')) {
		if($c['seo_title']) {
			$DT['seo_title'] = $city_sitename = $c['seo_title'];
		} else {
			$citysite = lang($L['citysite'], array($c['name']));
			$DT['seo_title'] = $citysite.$DT['seo_delimiter'].$DT['seo_title'];
			$city_sitename = $citysite.$DT['seo_delimiter'].$DT['sitename'];
		}
		if($c['seo_keywords']) $DT['seo_keywords'] = $c['seo_keywords'];
		if($c['seo_description']) $DT['seo_description'] = $c['seo_description'];
	}
	$city_name = $c['name'];
	$city_domain = $c['domain'];
	$city_template = $c['template'];
}
if($city_domain) {
	foreach($MODULE as $k=>$v) {
		if($v['islink']) continue;
		$MODULE[$k]['linkurl'] = $k == 1 ? $city_domain : $city_domain.$v['moduledir'].'/';
	}
	$MOD['linkurl'] = $MODULE[$moduleid]['linkurl'];
	foreach($EXT as $k=>$v) {
		if(strpos($k, '_url') !== false) {
			$EXT[$k] = $city_domain.str_replace('_url', '', $k).'/';
		}
	}
}
?>